'''
Created on 29/lug/2009

@author: Fabio
'''
from PyQt4 import QtCore, QtGui

class MapView( QtGui.QWidget ):
    def __init__( self, parent = None ):
        super( MapView, self ).__init__()
        self.setAcceptDrops( True )

        label = QtGui.QLabel()
        label.setMinimumSize( 30, 30 )
        label.move( 10, 10 )
        label.setPixmap( QtGui.QPixmap( ":piantina.jpg" ) )


        layout = QtGui.QGridLayout()
        layout.addWidget( label, 0, 0 )
        self.setLayout( layout )

    def dragEnterEvent( self, event ):
        if event.mimeData().hasFormat( "application/x-dnditemdata" ):
            if event.source() == self:
                event.setDropAction( QtCore.Qt.MoveAction )
                event.accept()
            else:
                event.acceptProposedAction()
        else:
            event.ignore()

    dragMoveEvent = dragEnterEvent

    def dropEvent( self, event ):
        if event.mimeData().hasFormat( "application/x-dnditemdata" ):
            itemData = event.mimeData().data( "application/x-dnditemdata" )
            dataStream = QtCore.QDataStream( itemData, QtCore.QIODevice.ReadOnly )

            pixmap = QtGui.QPixmap()
            offset = QtCore.QPoint()
            dataStream >> pixmap >> offset

            newIcon = QtGui.QLabel( self )
            newIcon.setPixmap( pixmap )
            newIcon.move( event.pos() - offset )
            newIcon.show()
            newIcon.setAttribute( QtCore.Qt.WA_DeleteOnClose )

            if event.source() == self:
                event.setDropAction( QtCore.Qt.MoveAction )
                event.accept()
            else:
                event.acceptProposedAction()
        else:
            event.ignore()

    def mousePressEvent( self, event ):

        child = self.childAt( event.pos() )
        if not child:
            return

        pixmap = QtGui.QPixmap( child.pixmap() )

        itemData = QtCore.QByteArray()
        dataStream = QtCore.QDataStream( itemData, QtCore.QIODevice.WriteOnly )
        dataStream << pixmap << QtCore.QPoint( event.pos() - child.pos() )

        mimeData = QtCore.QMimeData()
        mimeData.setData( "application/x-dnditemdata", itemData )

        drag = QtGui.QDrag( self )
        drag.setMimeData( mimeData )
        drag.setPixmap( pixmap )
        drag.setHotSpot( event.pos() - child.pos() )

        tempPixmap = QtGui.QPixmap( pixmap )
        painter = QtGui.QPainter()
        painter.begin( tempPixmap )
        painter.fillRect( pixmap.rect(), QtGui.QColor( 127, 127, 127, 127 ) )
        painter.end()

        child.setPixmap( tempPixmap )

        if drag.exec_( QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction ) == QtCore.Qt.MoveAction:
            child.close()
        else:
            child.show()
            child.setPixmap( pixmap )

